package com.ruoyi.framework.config;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceTransformer;
import org.springframework.web.servlet.resource.ResourceTransformerChain;
import org.springframework.web.servlet.resource.TransformedResource;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Swagger资源处理器，用于在Swagger UI中注入自定义认证脚本
 *
 * @author ruoyi
 */
@Component
public class SwaggerResourceHandler implements ResourceTransformer {

    @Override
    public Resource transform(HttpServletRequest request, Resource resource,
                            ResourceTransformerChain transformerChain) throws IOException {
        
        // 只处理swagger-ui.html文件
        if (resource.getFilename() != null && resource.getFilename().contains("swagger-ui")) {
            // 读取原始内容
            String content = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            
            // 在head标签中注入我们的认证脚本
            String authScript = "<script src=\"/swagger-auth.js\"></script>";
            
            // 在</head>标签前插入脚本
            if (content.contains("</head>")) {
                content = content.replace("</head>", authScript + "\n</head>");
            } else if (content.contains("<head>")) {
                // 如果没有</head>，在<head>后插入
                content = content.replace("<head>", "<head>\n" + authScript);
            } else {
                // 如果都没有，在文档开头插入
                content = authScript + "\n" + content;
            }
            
            return new TransformedResource(resource, content.getBytes(StandardCharsets.UTF_8));
        }
        
        return transformerChain.transform(request, resource);
    }
}